package com.example.flutter_activemq_plugin

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import androidx.annotation.NonNull
import com.google.gson.Gson
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*

/** FlutterActivemqPlugin */
class FlutterActivemqPlugin: FlutterPlugin, MethodCallHandler {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var mContext: Context

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    mContext = flutterPluginBinding.applicationContext
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_activemq_plugin")
    channel.setMethodCallHandler(this)
  }


  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    when (call.method) {
        "getPlatformVersion" -> {
          result.success("Android ${android.os.Build.VERSION.RELEASE}")
        }
        "connectMq" -> {
          val serverURI = call.argument<String>("serverURI")
          val topic = call.argument<String>("topic")
          try{
            connectToService(serverURI,topic)
//            result.success(true)
          }catch(e:Exception){
            e.printStackTrace()
//            result.success(false)
          }
        }
        else -> {
          result.notImplemented()
        }
    }
  }

  private fun connectToService(serverURI: String?, topic: String?) {
//    val serverURI = "ws://amq.dermat.cn:61614"
    val serverURI = "ws://$serverURI:61614"
    val clientId = "ANDROID_ID" + System.currentTimeMillis()
    val username = "app.consumer"
    val password = "DermatConsumer999"
//    val topic = "DIS05MQ"
    val mqClient = MqttAndroidClient(mContext, serverURI, clientId)
    val connectOptions = MqttConnectOptions()
    connectOptions.isAutomaticReconnect = true
    connectOptions.isCleanSession = true
    connectOptions.connectionTimeout = 5000
    connectOptions.keepAliveInterval = 90
    connectOptions.userName = username
    connectOptions.password = password.toCharArray()
    try {
      //后续监听
      mqClient.setCallback(object : MqttCallback {
        override fun connectionLost(cause: Throwable) {
          cause.printStackTrace()
        }

        @Throws(Exception::class)
        override fun messageArrived(topic: String, message: MqttMessage) {
          //接收消息
          //将监听到的消息，通过methchannel传给flutter
          Log.i("wangc", "messageArrived: ${message}");
          channel.invokeMethod("receiveMsg", "$message")
        }

        override fun deliveryComplete(token: IMqttDeliveryToken) {
          //发送、提交完成
          Log.i("wangc", "deliveryComplete: ")
        }
      })
      //连接
      mqClient.connect(connectOptions, null, object : IMqttActionListener {
        override fun onSuccess(asyncActionToken: IMqttToken) {
          Log.i("wangc", "连接成功," + asyncActionToken.client.serverURI)
          //订阅主题
          try {
            mqClient.subscribe(topic, 0, null, object : IMqttActionListener {
              override fun onSuccess(asyncActionToken: IMqttToken) {
                Log.i("wangc", "onSuccess: $asyncActionToken")
              }

              override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {}
            })
          } catch (e: MqttException) {
            e.printStackTrace()
          }
        }

        override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
          exception.printStackTrace()
        }
      })
    } catch (e: MqttException) {
      e.printStackTrace()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
}
